import pymysql
import threading
import math
from datetime import datetime

from db_info import dbs

def select(conn, sql):
    db = pymysql.connect(conn['ip'], conn['usr'], conn['pwd'], conn['database'])
    cursor = db.cursor(cursor = pymysql.cursors.DictCursor)
    try:
        cursor.execute(sql)
        data = cursor.fetchall()
        return data
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        db.close()

def select2(cursor, sql):
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

def tbl_find(data, target, equ, all):
    for i in data:
        count = 0
        for j in i:
            cell = str(i[j])
            fKey = ''
            fValue = ''
            if 0 == count:
                fKey = j
                fValue = cell
            if equ:
                if cell == target:
                    print(f'fKey: {fKey}, fValue: {fValue}, field: {j}, value: {cell}')
            else:
                if target in cell:
                    print(f'fKey: {fKey}, fValue: {fValue}, field: {j}, value: {cell}')

def split_list(li, n):
    result = [[]]
    count = 0
    len_li = len(li)
    for i in li:
        result[len(result) - 1].append(i)
        count += 1
        if count % math.ceil(len_li / n) == 0 and len_li != count:
            result.append([])
    return result

class Tbl_thread(threading.Thread):
    def __init__(self, name, conn, tbls, target, equ, all):
        threading.Thread.__init__(self)
        self.name = name
        self.conn = conn
        self.tbls = tbls
        self.target = target
        self.equ = equ
        self.all = all
    def run(self):
        print(f'start: {self.name}')
        conn = self.conn
        db = pymysql.connect(conn['ip'], conn['usr'], conn['pwd'], conn['database'])
        cursor = db.cursor(cursor = pymysql.cursors.DictCursor)
        for i in self.tbls:
            try:
                data = select2(cursor, f'select * from {i}')
            except Exception as e:
                print(e)
                break
            tbl_find(data, self.target, self.equ, self.all)
        cursor.close()
        db.close()
        print(f'end: {self.name}')

if __name__ == '__main__':
    start = datetime.now()
    threads = []
    for i in dbs:
        tbls = select(dbs[i], 'show tables;')
        tbls2 = []
        for j in tbls:
            for k in j:
                tbls2.append(j[k])
        tbls3 = split_list(tbls2, 3)
        count = 1
        for j in tbls3:
            threads.append(Tbl_thread(f'{i}-{count}', dbs[i], j, '管理员', False, True))
            count += 1
    for i in threads:
        i.start()
    for i in threads:
        i.join()
    end = datetime.now()
    print(end - start)
    print('end')

